<template>
  <div class="user-manage-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>用户管理</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="handleRefresh"
        >刷新</el-button>
      </div>
      
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="queryParams.role" placeholder="请选择角色" clearable>
            <el-option label="管理员" value="ADMIN"></el-option>
            <el-option label="普通用户" value="USER"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 表格区域 -->
      <el-table
        :data="userList"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column prop="username" label="用户名" align="center"></el-table-column>
        <el-table-column prop="name" label="姓名" align="center"></el-table-column>
        <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
        <el-table-column prop="email" label="邮箱" align="center"></el-table-column>
        <el-table-column prop="role" label="角色" align="center">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.role === 'ADMIN'">管理员</el-tag>
            <el-tag v-else>普通用户</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.createTime | formatDate }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)"
              icon="el-icon-edit"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              icon="el-icon-delete"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
      ></el-pagination>
      
      <!-- 编辑用户对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%">
        <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username" :disabled="editMode"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="userForm.name"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="userForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userForm.email"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="userForm.role" placeholder="请选择角色">
              <el-option label="管理员" value="ADMIN"></el-option>
              <el-option label="普通用户" value="USER"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="!editMode">
            <el-input v-model="userForm.password" type="password"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'UserManage',
  data() {
    return {
      // 查询参数
      queryParams: {
        username: '',
        role: '',
        pageNum: 1,
        pageSize: 10
      },
      // 用户列表
      userList: [],
      // 总记录数
      total: 0,
      // 加载状态
      loading: false,
      // 对话框可见性
      dialogVisible: false,
      // 对话框标题
      dialogTitle: '',
      // 是否为编辑模式
      editMode: false,
      // 用户表单
      userForm: {
        id: '',
        username: '',
        name: '',
        phone: '',
        email: '',
        role: 'USER',
        password: ''
      },
      // 表单验证规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 获取用户列表
    this.getUserList()
  },
  filters: {
    // 日期格式化过滤器
    formatDate(time) {
      if (!time) return ''
      const date = new Date(time)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
    }
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      this.loading = true
      try {
        const { data: res } = await this.$http.get('/user/list', {
          params: this.queryParams
        })
        if (res.code !== 200) {
          return this.$message.error(res.message || '获取用户列表失败')
        }
        this.userList = res.data.records
        this.total = res.data.total
      } catch (error) {
        console.error('获取用户列表失败', error)
        this.$message.error('获取用户列表失败')
      } finally {
        this.loading = false
      }
    },
    // 处理查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getUserList()
    },
    // 重置查询
    resetQuery() {
      this.queryParams = {
        username: '',
        role: '',
        pageNum: 1,
        pageSize: 10
      }
      this.getUserList()
    },
    // 处理刷新
    handleRefresh() {
      this.getUserList()
    },
    // 处理页码变化
    handleCurrentChange(pageNum) {
      this.queryParams.pageNum = pageNum
      this.getUserList()
    },
    // 处理每页条数变化
    handleSizeChange(pageSize) {
      this.queryParams.pageSize = pageSize
      this.queryParams.pageNum = 1
      this.getUserList()
    },
    // 处理编辑
    handleEdit(row) {
      this.dialogTitle = '编辑用户'
      this.editMode = true
      this.userForm = { ...row }
      this.dialogVisible = true
    },
    // 处理删除
    handleDelete(row) {
      this.$confirm(`确认删除用户 ${row.username} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const { data: res } = await this.$http.delete(`/user/${row.id}`)
          if (res.code !== 200) {
            return this.$message.error(res.message || '删除用户失败')
          }
          this.$message.success('删除用户成功')
          this.getUserList()
        } catch (error) {
          console.error('删除用户失败', error)
          this.$message.error('删除用户失败')
        }
      }).catch(() => {
        // 取消删除
      })
    },
    // 提交表单
    submitForm() {
      this.$refs.userFormRef.validate(async valid => {
        if (!valid) return
        try {
          let res
          if (this.editMode) {
            // 编辑用户
            res = await this.$http.put('/user/info', this.userForm)
          } else {
            // 添加用户
            res = await this.$http.post('/user/register', this.userForm)
          }
          if (res.data.code !== 200) {
            return this.$message.error(res.data.message || '操作失败')
          }
          this.$message.success('操作成功')
          this.dialogVisible = false
          this.getUserList()
        } catch (error) {
          console.error('操作失败', error)
          this.$message.error('操作失败')
        }
      })
    }
  }
}
</script>

<style scoped>
.user-manage-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>